package city.spring.modules.medicine.controller;

import city.spring.modules.medicine.entity.MedicinereceiptEntity;
import city.spring.modules.medicine.service.MedicineService;
import city.spring.modules.medicine.service.MedicinereceiptService;
import city.spring.modules.medicine.vo.MedicinereceiptVO;
import city.spring.modules.system.service.OrganizationService;
import city.spring.modules.system.service.UserService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.NonNull;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.data.web.SortDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Controller：药品领用申请
 *
 * @author 谢金婷
 * @date 2020-06-27 11:27:59
 */
@RestController
@RequestMapping("/medicinereceipt")
public class MedicinereceiptController extends ApiController {
    private final MedicinereceiptService medicinereceiptService;
    private final UserService userService;
    private final OrganizationService organizationService;
    private final MedicineService medicineService;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<MedicinereceiptEntity, ?>> entityOrderFields;

    public MedicinereceiptController(MedicinereceiptService medicinereceiptService, UserService userService, OrganizationService organizationService, MedicineService medicineService) {
        this.medicinereceiptService = medicinereceiptService;
        this.userService = userService;
        this.organizationService = organizationService;
        this.medicineService = medicineService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(MedicinereceiptEntity::getId);
        entityOrderFields.add(MedicinereceiptEntity::getRtype);
        entityOrderFields.add(MedicinereceiptEntity::getReceipter);
        entityOrderFields.add(MedicinereceiptEntity::getDepartment);
        entityOrderFields.add(MedicinereceiptEntity::getApplicationdate);
        entityOrderFields.add(MedicinereceiptEntity::getApplication);
        entityOrderFields.add(MedicinereceiptEntity::getReviewer);
        entityOrderFields.add(MedicinereceiptEntity::getReviewdate);
        entityOrderFields.add(MedicinereceiptEntity::getMedicineId);
        entityOrderFields.add(MedicinereceiptEntity::getUnitmeasurement);
        entityOrderFields.add(MedicinereceiptEntity::getQuantity);
        entityOrderFields.add(MedicinereceiptEntity::getRemark);
        entityOrderFields.add(MedicinereceiptEntity::getApprovalStatus);
        entityOrderFields.add(MedicinereceiptEntity::getDeliveryStatus);
        entityOrderFields.add(MedicinereceiptEntity::getGmtCreate);
        entityOrderFields.add(MedicinereceiptEntity::getGmtModified);
    }

    /**
     * 获取全部的 <strong>药品领用申请</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault Pageable pageable, MedicinereceiptEntity entity) {
        LambdaQueryChainWrapper<MedicinereceiptEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    /**
     * 分页获取 <strong>药品领用申请</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping
    public Object list(@PageableDefault @SortDefault.SortDefaults({@SortDefault(sort = "id", direction = Sort.Direction.DESC)}) Pageable pageable, MedicinereceiptVO entity, Date[] applicationdate) {


        QueryWrapper<? extends MedicinereceiptEntity> queryWrapper = buildQuery(entity);
        if (applicationdate != null && applicationdate.length == 2) {
            queryWrapper.ge("t1.applicationdate", applicationdate[0]);
            queryWrapper.le("t1.applicationdate", applicationdate[1]);
        }
        return success(medicinereceiptService.listPage(MyBatisUtils.toPage(pageable), queryWrapper));

//        LambdaQueryChainWrapper<MedicinereceiptEntity> lambdaQuery = buildLambdaQuery(entity);
//        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
//        Page<MedicinereceiptEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
//        for (MedicinereceiptEntity record : page.getRecords()) {
//            try {
//                UserEntity userEntity = userService.getById(record.getReceipter());
//                record.setNickname(userEntity.getNickname());
//            } catch (Exception ignore) {
//                record.setReceipter(null);
//                record.setNickname("< 找不到领用人员 >");
//            }
//        }
//        for (MedicinereceiptEntity record : page.getRecords()) {
//            try {
//                OrganizationEntity organizationEntity = organizationService.getById(record.getDepartment());
//                System.out.println(organizationEntity);
//                record.setTitle(organizationEntity.getTitle());
//            } catch (Exception ignore) {
//                record.setDepartment(null);
//                record.setTitle("< 找不到部门 >");
//            }
//        }
//        for (MedicinereceiptEntity record : page.getRecords()) {
//            try {
//                MedicineEntity medicineEntity = medicineService.getById(record.getMedicineId());
//                record.setMname(medicineEntity.getName());
//            } catch (Exception ignore) {
//                record.setMedicineId(null);
//                record.setMname("< 找不到药品 >");
//            }
//        }
//        for (MedicinereceiptEntity record : page.getRecords()) {
//            try {
//                UserEntity userEntity = userService.getById(record.getReviewer());
//                record.setUserReviewer(userEntity.getUsername());
//            } catch (Exception ignore) {
//                record.setReviewer(null);
//                record.setUserReviewer("< 找不到审核人员 >");
//            }
//        }
//        return success(page);
    }

    @GetMapping("/approvalList")
    public Object approvalList(@PageableDefault @SortDefault.SortDefaults({@SortDefault(sort = "id", direction = Sort.Direction.DESC)}) Pageable pageable, MedicinereceiptVO entity, Date[] applicationdate) {

        QueryWrapper<? extends MedicinereceiptEntity> queryWrapper = buildQueryApprovalList(entity);
        if (applicationdate != null && applicationdate.length == 2) {
            queryWrapper.ge("t1.applicationdate", applicationdate[0]);
            queryWrapper.le("t1.applicationdate", applicationdate[1]);
        }
        return success(medicinereceiptService.approvalListPage(MyBatisUtils.toPage(pageable), queryWrapper));
    }

    @GetMapping("/deliveryList")
    public Object deliveryList(@PageableDefault @SortDefault.SortDefaults({@SortDefault(sort = "id", direction = Sort.Direction.DESC)}) Pageable pageable, MedicinereceiptVO entity, Date[] applicationdate) {

        QueryWrapper<? extends MedicinereceiptEntity> queryWrapper = buildQueryDeliveryList(entity);
        if (applicationdate != null && applicationdate.length == 2) {
            queryWrapper.ge("t1.applicationdate", applicationdate[0]);
            queryWrapper.le("t1.applicationdate", applicationdate[1]);
        }
        return success(medicinereceiptService.deliveryListPage(MyBatisUtils.toPage(pageable), queryWrapper));
    }


    /**
     * 获取一个 <strong>药品领用申请</strong>
     *
     * @param id 主键ID
     */
    @GetMapping("{id}")
    public Object info(@PathVariable String id) {
//        return success(medicinereceiptService.getById(id));

        QueryWrapper<MedicinereceiptVO> wrapper = new QueryWrapper<>();
        wrapper.eq("t1.id", id);
        List<MedicinereceiptVO> records = medicinereceiptService.listPage(new Page<>(), wrapper).getRecords();
        if (records.isEmpty()) {
            return success(null);
        }
        return success(records.get(0));
    }

    @GetMapping("/approvalList/{id}")
    public Object approvalListPageinfo(@PathVariable String id) {

//        return success(receiptService.getById(id));

        QueryWrapper<MedicinereceiptVO> wrapper = new QueryWrapper<>();
        wrapper.eq("t1.id", id);
        List<MedicinereceiptVO> records = medicinereceiptService.approvalListPage(new Page<>(), wrapper).getRecords();
        if (records.isEmpty()) {
            return success(null);
        }
        return success(records.get(0));
    }

    @GetMapping("/deliveryList/{id}")
    public Object deliveryListPageinfo(@PathVariable String id) {

//        return success(receiptService.getById(id));

        QueryWrapper<MedicinereceiptVO> wrapper = new QueryWrapper<>();
        wrapper.eq("t1.id", id);
        List<MedicinereceiptVO> records = medicinereceiptService.deliveryListPage(new Page<>(), wrapper).getRecords();
        if (records.isEmpty()) {
            return success(null);
        }
        return success(records.get(0));
    }

    /**
     * 添加一个 <strong>药品领用申请</strong>
     *
     * @param entity 修改后的信息
     */
    @PostMapping
    public Object add(@RequestBody MedicinereceiptEntity entity, @NonNull Principal user) {
        medicinereceiptService.saveMedicinereceipt(entity, user);

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
        return new ResponseEntity<>(headers, HttpStatus.CREATED);
    }

    /**
     * 修改一个 <strong>药品领用申请</strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PutMapping("{id}")
    public Object update(@PathVariable String id, @RequestBody MedicinereceiptEntity entity) {
        entity.setId(Integer.valueOf(id));
        medicinereceiptService.updateMedicinereceipt(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong>药品领用申请</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        medicinereceiptService.deleteMedicinereceipt(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>药品领用申请</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        medicinereceiptService.deleteMedicinereceipt(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<MedicinereceiptEntity> buildLambdaQuery(MedicinereceiptEntity entity) {
        LambdaQueryChainWrapper<MedicinereceiptEntity> lambdaQuery = medicinereceiptService.lambdaQuery();
        lambdaQuery.eq(entity.getId() != null, MedicinereceiptEntity::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getRtype()), MedicinereceiptEntity::getRtype, entity.getRtype());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getReceipter()), MedicinereceiptEntity::getReceipter, entity.getReceipter());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getDepartment()), MedicinereceiptEntity::getDepartment, entity.getDepartment());
        lambdaQuery.eq(entity.getApplicationdate() != null, MedicinereceiptEntity::getApplicationdate, entity.getApplicationdate());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getApplication()), MedicinereceiptEntity::getApplication, entity.getApplication());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getReviewer()), MedicinereceiptEntity::getReviewer, entity.getReviewer());
        lambdaQuery.eq(entity.getReviewdate() != null, MedicinereceiptEntity::getReviewdate, entity.getReviewdate());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getMedicineId()), MedicinereceiptEntity::getMedicineId, entity.getMedicineId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getUnitmeasurement()), MedicinereceiptEntity::getUnitmeasurement, entity.getUnitmeasurement());
        lambdaQuery.eq(entity.getQuantity() != null, MedicinereceiptEntity::getQuantity, entity.getQuantity());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getRemark()), MedicinereceiptEntity::getRemark, entity.getRemark());
        lambdaQuery.eq(entity.getApprovalStatus() != null, MedicinereceiptEntity::getApprovalStatus, entity.getApprovalStatus());
        lambdaQuery.eq(entity.getDeliveryStatus() != null, MedicinereceiptEntity::getDeliveryStatus, entity.getDeliveryStatus());
        lambdaQuery.eq(entity.getGmtCreate() != null, MedicinereceiptEntity::getGmtCreate, entity.getGmtCreate());
        lambdaQuery.eq(entity.getGmtModified() != null, MedicinereceiptEntity::getGmtModified, entity.getGmtModified());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<MedicinereceiptEntity> buildQuery(MedicinereceiptVO entity) {
        QueryWrapper<MedicinereceiptEntity> wrapper = new QueryWrapper<>();
        wrapper.like(entity.getId() != null, "t1.id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getRtype()), "t1.rtype", entity.getRtype());
        wrapper.like(StringUtils.isNotBlank(entity.getReceipter()), "t1.receipter", entity.getReceipter());
        wrapper.like(StringUtils.isNotBlank(entity.getNickname()), "t2.name", entity.getNickname());
        wrapper.like(StringUtils.isNotBlank(entity.getDepartment()), "t1.department", entity.getDepartment());
        wrapper.like(StringUtils.isNotBlank(entity.getTitle()), "t3.title", entity.getTitle());
        wrapper.like(StringUtils.isNotBlank(entity.getReviewer()), "t1.reviewer", entity.getReviewer());
        wrapper.like(StringUtils.isNotBlank(entity.getUserReviewer()), "t4.name", entity.getUserReviewer());
        wrapper.like(StringUtils.isNotBlank(entity.getMedicineId()), "t1.medicine_id", entity.getMedicineId());
        wrapper.like(StringUtils.isNotBlank(entity.getMname()), "t5.name", entity.getMname());
        wrapper.like(entity.getApprovalStatus() != null, "t1.approval_status", entity.getApprovalStatus());
        wrapper.like(entity.getDeliveryStatus() != null, "t1.delivery_status", entity.getDeliveryStatus());
//        wrapper.like(entity.getApplicationdate() != null, "t3.applicationdate", entity.getApplicationdate());
        return wrapper;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<MedicinereceiptEntity> buildQueryApprovalList(MedicinereceiptVO entity) {
        QueryWrapper<MedicinereceiptEntity> wrapper = new QueryWrapper<>();
        wrapper.like(entity.getId() != null, "t1.id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getRtype()), "t1.rtype", entity.getRtype());
        wrapper.like(StringUtils.isNotBlank(entity.getReceipter()), "t1.receipter", entity.getReceipter());
        wrapper.like(StringUtils.isNotBlank(entity.getNickname()), "t2.name", entity.getNickname());
        wrapper.like(StringUtils.isNotBlank(entity.getDepartment()), "t1.department", entity.getDepartment());
        wrapper.like(StringUtils.isNotBlank(entity.getTitle()), "t3.title", entity.getTitle());
        wrapper.like(StringUtils.isNotBlank(entity.getReviewer()), "t1.reviewer", entity.getReviewer());
        wrapper.like(StringUtils.isNotBlank(entity.getUserReviewer()), "t4.name", entity.getUserReviewer());
        wrapper.like(StringUtils.isNotBlank(entity.getMedicineId()), "t1.medicine_id", entity.getMedicineId());
        wrapper.like(StringUtils.isNotBlank(entity.getMname()), "t5.name", entity.getMname());
        wrapper.like(entity.getApprovalStatus() != null, "t1.approval_status", entity.getApprovalStatus());
        wrapper.like(entity.getDeliveryStatus() != null, "t1.delivery_status", entity.getDeliveryStatus());
//        wrapper.like(entity.getApplicationdate() != null, "t3.applicationdate", entity.getApplicationdate());
        return wrapper;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<MedicinereceiptEntity> buildQueryDeliveryList(MedicinereceiptVO entity) {
        QueryWrapper<MedicinereceiptEntity> wrapper = new QueryWrapper<>();
        wrapper.like(entity.getId() != null, "t1.id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getRtype()), "t1.rtype", entity.getRtype());
        wrapper.like(StringUtils.isNotBlank(entity.getReceipter()), "t1.receipter", entity.getReceipter());
        wrapper.like(StringUtils.isNotBlank(entity.getNickname()), "t2.name", entity.getNickname());
        wrapper.like(StringUtils.isNotBlank(entity.getDepartment()), "t1.department", entity.getDepartment());
        wrapper.like(StringUtils.isNotBlank(entity.getTitle()), "t3.title", entity.getTitle());
        wrapper.like(StringUtils.isNotBlank(entity.getReviewer()), "t1.reviewer", entity.getReviewer());
        wrapper.like(StringUtils.isNotBlank(entity.getUserReviewer()), "t4.name", entity.getUserReviewer());
        wrapper.like(StringUtils.isNotBlank(entity.getMedicineId()), "t1.medicine_id", entity.getMedicineId());
        wrapper.like(StringUtils.isNotBlank(entity.getMname()), "t5.name", entity.getMname());
        wrapper.like(entity.getApprovalStatus() != null, "t1.approval_status", entity.getApprovalStatus());
        wrapper.like(entity.getDeliveryStatus() != null, "t1.delivery_status", entity.getDeliveryStatus());
//        wrapper.like(entity.getApplicationdate() != null, "t3.applicationdate", entity.getApplicationdate());
        return wrapper;
    }

    /**
     * 根据id查询药品领用申请信息
     *
     * @param id
     * @return
     */
    @GetMapping("/getMedicinereceiptById/{id}")
    public Object getMedicinereceiptById(@PathVariable String id) {
        return success(medicinereceiptService.getMedicinereceiptById(id));
    }

    /**
     * 获取审核通过的领用申请信息
     *
     * @param pageable
     * @return
     */
    @GetMapping("/getMedicinereceiptPass")
    public Object getMedicinereceiptPass(Pageable pageable) {
        return success(medicinereceiptService.getMedicinereceiptPass(pageable));
    }

    /**
     * 获取非审核通过的领用申请信息
     *
     * @param pageable
     * @return
     */
    @GetMapping("/getMedicinereceiptNoPass")
    public Object getMedicinereceiptNoPass(Pageable pageable) {
        return success(medicinereceiptService.getMedicinereceiptNoPass(pageable));
    }


    /**
     * 统计最大可领用数量
     * 现有库存-待出库数量（领用待审核数量）
     *
     * @param name
     * @param category
     * @param specifications
     * @param unit
     * @param dosageunit
     * @return
     */
    @GetMapping("/getOptionalQuantity")
    public BigDecimal getOptionalQuantity(String name, String category, String specifications, String type, String unit, String dosageunit) {
        return medicinereceiptService.getOptionalQuantity(name, category, specifications, type, unit, dosageunit);

    }


}
